package com.photoeditor.demo.model.face.report.reportlogic;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.android.gpuimage.GPUImage;
import com.android.gpuimage.GPUImageFilter;
import com.android.gpuimage.GPUImageLookupFilter;
import com.android.gpuimage.GPUImageTextureFilter;
import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.thread.ThreadPool;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.photoeditor.R;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.bean.face.FaceDetectBeanV4;
import com.photoeditor.demo.model.event.GotoAdVideoPageEvent;
import com.photoeditor.demo.model.event.GotoSubscribePageEvent;
import com.photoeditor.demo.model.event.VipMaskIsShowEvent;
import com.photoeditor.demo.model.face.FaceConstant;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.activity.face.FaceLogicActivity;
import com.photoeditor.demo.ui.widget.face.ExpandableTextView;
import com.photoeditor.demo.util.APKAssertImageLoader;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.BitmapUtils;
import com.photoeditor.demo.util.BlurUtil;
import com.photoeditor.demo.util.FastBlur;
import com.photoeditor.demo.util.NetworkUtils;
import com.photoeditor.demo.util.TimeConstant;
import com.photoeditor.demo.util.ToastUtil;
import com.photoeditor.demo.util.face.FaceBaseCallback;
import com.photoeditor.demo.util.face.FaceUtil;
import com.photoeditor.demo.util.transformation.BlurTransformation;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;

import static com.photoeditor.demo.model.bean.face.BaseFaceResultBean.REPORT_TYPE_PAST_LIFE;
import static com.photoeditor.demo.model.preference.SpUtils.EFFECT_NAME;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_10;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_4;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_6;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_ABOVE_10;
import static com.photoeditor.demo.util.measureTextViewSizeUtils.measureTextViewSize;

/**
 * Created by @author winn on 2018/10/30.
 */

public class PastLifeReportLogic extends BaseReportLogic {

    private final String TAG = PastLifeReportLogic.class.getSimpleName();

    private FaceDetectBeanV4 mResultBean;
    private ImageView mImgResult;
    private LottieAnimationView mLoadingView;
    private TextView mTvBirthYear, mTvLife, mTvCareer;
    private ExpandableTextView mProfileContent, mLessonContent;
    private ViewGroup mLifeLayout, mLessonLayout;

    private Context mContext;

    private View mGenderSwitchView;
    private View mContainerView;
    private View mMaskLayout;

    private boolean mIsLoading;
    private String mImagePath;
    private String mCompressPic;
    private String mResultBase64;
    private String mCurrentPath;
    private Bitmap mOriBitmap;
    private Bitmap mBluredUserBitmap;
    private Bitmap mBluredScreenBitmap;
    private Bitmap mProcessedBitmap;
    private boolean mIsModel;

    private Activity mActivity;

    public PastLifeReportLogic(String imagePath) {
        super(REPORT_TYPE_PAST_LIFE);
        mImagePath = imagePath;
    }

    public void setActivity(Activity activity) {
        mActivity = activity;
    }

    @Override
    public View getReportView(ViewGroup parent) {
        mContext = parent.getContext();
        ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.report_past_life, parent, false);
        initView(viewGroup);

        updateViewIfNecessary();
        return viewGroup;
    }

    private void initView(View rootView) {
        mContentView = rootView;
        mImgResult = rootView.findViewById(R.id.iv_effect);
        mLoadingView = rootView.findViewById(R.id.loading_animation_view);
        mGenderSwitchView = rootView.findViewById(R.id.layout_past_life);
        mContainerView = rootView.findViewById(R.id.pic_container);
        mTvBirthYear = rootView.findViewById(R.id.tv_birth_year_value);
        mTvLife = rootView.findViewById(R.id.tv_life_value);
        mTvCareer = rootView.findViewById(R.id.tv_career_value);
        mProfileContent = rootView.findViewById(R.id.profile_content);
        mLessonContent = rootView.findViewById(R.id.lesson_content);
        mLifeLayout = rootView.findViewById(R.id.profile_layout);
        mLifeLayout.setVisibility(View.GONE);
        mLessonLayout = rootView.findViewById(R.id.lesson_layout);
        mLessonLayout.setVisibility(View.GONE);

    }

    /**
     * 初始化或更换照片时调用，初始化头像及相关文案
     */
    private void updateUserView() {
        mIsModel = FaceConstant.isModel(mImagePath);
        if (mIsModel) {
            mOriBitmap = APKAssertImageLoader.with(mContext.getResources()).load(mImagePath).get();
        } else {
            mOriBitmap = BitmapFactory.decodeFile(mImagePath);
            if (mOriBitmap != null && FaceLogicActivity.degree != 0){  //旋转
                Matrix m = new Matrix();
                m.setRotate(FaceLogicActivity.degree, (float) mOriBitmap.getWidth() / 2, (float) mOriBitmap.getHeight() / 2);
                try {
                    mOriBitmap = Bitmap.createBitmap(mOriBitmap, 0, 0, mOriBitmap.getWidth(), mOriBitmap.getHeight(), m, true);
                } catch (OutOfMemoryError ex) {
                    //
                }
            }
        }
        mCurrentPath = mImagePath;

        mImgResult.setImageBitmap(mOriBitmap);

        mTvBirthYear.setText("");
        mTvLife.setText("");
        mTvCareer.setText("");
        mProfileContent.setText("");
        mLessonContent.setText("");
        mLifeLayout.setVisibility(View.GONE);
        mLessonLayout.setVisibility(View.GONE);
    }

    /**
     * 更新用户头像和文案、设置/重置非vip遮罩
     */
    private void updateViewIfNecessary() {
        updateUserView();
        checkVipView();
        checkModelRequest();
    }

    /**
     * 重置和用户图像相关的数据
     */
    private void resetData() {
        mIsModel = false;
        mResultBean = null;
        mResultBase64 = null;        //请求结果

        mProcessedBitmap = null;
        mBluredUserBitmap = null;
        mBluredScreenBitmap = null;
    }

    /**
     * model的假loading请求
     * 2s后展示结果
     */
    private void checkModelRequest() {
        if (!mIsModel) {
            return;
        }
        showLoading();
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                hideLoading();
                setDefaultModelView();
                if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                    ((FaceLogicActivity) mActivity).fakeScanReqSucc();
                }
            }
        }, 2000);
    }

    private void setDefaultModelView() {
        if (mIsModel) {
            //设置头像
            String path = FaceConstant.getModelPastLife(mImagePath);
            mProcessedBitmap = APKAssertImageLoader.with(mContext.getResources()).load(path).get();
            mImgResult.setImageBitmap(mProcessedBitmap);
            //模特图设置默认文字
            mTvBirthYear.setText("1894");
            mTvLife.setText("67");
            mTvCareer.setText("Doctor");
            mProfileContent.setText("As a natural talent in psychology, you knew how to use your opportunities. Cold-blooded and calm in any situation.");
            mLessonContent.setText("You lesson is to develop a kind attitude towards people, and to acquire the gift of understanding and compassion.");
            mLifeLayout.setVisibility(View.VISIBLE);
            mLessonLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 用户重新选择图像
     *
     * ！！！不需要启动请求，请求由activity启动，先检测人脸，成功后才回来二次请求
     */
    @Override
    public void updateImage(String image) {
        if (TextUtils.equals(mImagePath, image)) {
            return;
        }
        mImagePath = image;
        if (FaceConstant.isModel(mImagePath)) {
            if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).fakeScanReq();
            }
        }
        resetData();
        updateViewIfNecessary();
    }

    public void setResultBean(FaceDetectBeanV4 resultBean) {
        mResultBean = resultBean;
        updateState();
    }

    private void updateState() {
        if (AppVipManager.isVip()) {
            if (!TextUtils.isEmpty(mResultBase64)) {
                if (mResultBase64.equals(mCurrentPath)) {
                    return;
                }
                showSwapPic(mResultBase64);
                return;
            }
            mImgResult.setImageBitmap(mOriBitmap);
            mCurrentPath = mImagePath;
            compressAndRequest();
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.switch_image:
                if (mOnEventListener != null) {
                    mOnEventListener.switchImage();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onSubscribeSuccess() {
        updateViewIfNecessary();
        updateState();
    }

    private void createBluredMaskBitmap() {
        if (mMaskLayout != null) {
            View activityView = mContainerView;
            activityView.setDrawingCacheEnabled(true);
            activityView.destroyDrawingCache();
            activityView.buildDrawingCache();
            Bitmap bmp = activityView.getDrawingCache();
            if (bmp != null) {
                Bitmap copy = bmp.copy(Bitmap.Config.ARGB_8888, true);
                BlurUtil.blur(ComponentContext.getContext(), copy, 10);
                BlurUtil.drawDarkCover(copy);
                mBluredScreenBitmap = copy;
            }
            activityView.destroyDrawingCache();
            activityView.setDrawingCacheEnabled(false);
        }
    }

    private void createBluredUserBitmap(Bitmap srcBitmap) {
        int scaleRatio = 5;
        if (srcBitmap == null || srcBitmap.isRecycled()) {
            return;
        }
        Bitmap blurBitmap = srcBitmap.createScaledBitmap(srcBitmap,
                srcBitmap.getWidth() / scaleRatio,
                srcBitmap.getHeight() / scaleRatio,
                false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            blurBitmap = BlurTransformation.blur(ComponentContext.getContext(), blurBitmap, 5);
        } else {
            blurBitmap = FastBlur.doBlur(blurBitmap, 5, true);
        }
        Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBluredUserBitmap = Bitmap.createBitmap(blurBitmap.getWidth(), blurBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas1 = new Canvas(mBluredUserBitmap);
        canvas1.drawBitmap(blurBitmap, 0, 0, bitmapPaint);
    }

    /**
     * 非vip用户弹出遮罩
     */
    private void checkVipView() {
        if (AppVipManager.isVip() || mIsModel) {
            if (mMaskLayout != null) {
                mMaskLayout.setVisibility(View.INVISIBLE);
            }
            return;
        }
        if (mMaskLayout != null) {
            createBluredUserBitmap(mOriBitmap);                 //生成用户模糊图片
            mImgResult.setImageBitmap(mBluredUserBitmap);       //设置用户模糊图片
            ThreadPool.runUITask(new Runnable() {               //设置全屏非Vip遮罩
                @Override
                public void run() {
                    createBluredMaskBitmap();
                    if (mBluredScreenBitmap != null) {
//                        mMaskLayout.setBackground(new BitmapDrawable(mBluredScreenBitmap));
                        BlurUtil.applyBlur((Activity) mContext, mMaskLayout);
                    }
                }
            }, 100);
            mMaskLayout.setVisibility(View.VISIBLE);
            return;
        }
        //初始化非vip布局
        ViewStub maskStub = (ViewStub) mContentView.findViewById(R.id.stub_subscribe_mask);
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_SHOW,
                StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE,
                StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE);
        mMaskLayout = maskStub.inflate();
        AppCompatTextView textView=mMaskLayout.findViewById(R.id.btn_vip_confirm);
        measureTextViewSize(mActivity,textView,200);
        createBluredUserBitmap(mOriBitmap);             //生成用户模糊图片
        mImgResult.setImageBitmap(mBluredUserBitmap);   //设置用户模糊图片
        ThreadPool.runUITask(new Runnable() {           //设置全屏非Vip遮罩
            @Override
            public void run() {
                createBluredMaskBitmap();
                if (mBluredScreenBitmap != null) {
//                    mMaskLayout.setBackground(new BitmapDrawable(mBluredScreenBitmap));
                    BlurUtil.applyBlur((Activity) mContext, mMaskLayout);
                }
            }
        }, 100);
        if ((SPDataManager.getTodayHasShowedNorStickersSubscribeMaskCount() < 3)) {
            DLog.d("wLog", "前2次显示模糊页，则页面上不显示激励视频按钮，" +
                    "并在进入模糊页后自动跳转到主订阅页，从主订阅页返回到模糊页，并显示激励视频解锁按钮");
            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
            lps.bottomMargin = DeviceUtils.dip2px(24);
            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.GONE);
        }

        //策略平台控制，0——旧样式，1——AD弹框，2——评分引导一天免费弹框
//        RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
//        if (SPDataManager.isFirstCloseSubsPage() || ((beanConfig == null || beanConfig.getRateType() != ADVANCE_OBTAIN_RESULT))) {
//            //模糊页不展示watch video按钮
//            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
//            lps.bottomMargin = DeviceUtils.dip2px(24);
//            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
//            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.GONE);
//        }
        mMaskLayout.findViewById(R.id.rl_continue_vip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_BUTT_CLICK,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE);
                //跳转到订阅页面
                EventBus.getDefault().post(new GotoSubscribePageEvent());
            }
        });
        mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到激励视频
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE);
                SpUtils.obtain().save(EFFECT_NAME, "past");
                EventBus.getDefault().post(new GotoAdVideoPageEvent());
            }
        });

        if (mMaskLayout.findViewById(R.id.rip_ll_watch_ad).getVisibility() == View.VISIBLE){
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                    StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                    StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_PAST_LIFE,
                    StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE);
        }

        if (mMaskLayout.getVisibility() == View.VISIBLE) {
            ThreadPool.runUITask(new Runnable() {               //设置全屏非Vip遮罩
                @Override
                public void run() {
                    EventBus.getDefault().post(new VipMaskIsShowEvent());
                }
            }, 1000);
        }
    }

    /**
     * 首次订阅页返回时调用
     */
    public void updateMaskLayout() {
        if (AppVipManager.isVip()) {
            return;
        }
        if (mMaskLayout != null) {
            checkVipView();
            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
            lps.bottomMargin = DeviceUtils.dip2px(0);
            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.VISIBLE);
            if (mMaskLayout.findViewById(R.id.rip_ll_watch_ad).getVisibility() == View.VISIBLE){
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_PAST_LIFE,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE);
            }
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
//                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
//                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_PAST_LIFE);
//            RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
//            if ((beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)) {
//                RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
//                lps.bottomMargin = DeviceUtils.dip2px(0);
//                mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
//                mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.VISIBLE);
////                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
////                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
////                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_PAST_LIFE);
//            }
        }
    }

    private void startRequest() {
        mIsLoading = true;
    }

    private void stopRequest() {
        mIsLoading = false;
    }

    public boolean isLoading() {
        return mIsLoading;
    }

    /**
     * 获取接口请求的耗时区间
     *
     * @param startRequest 开始请求时间
     * @return 区间文本
     */
    private String getTimeInterval(long startRequest) {
        long successRequest = System.currentTimeMillis();
        long diff = successRequest - startRequest;
        float second = diff / 1000f;
        String secondText = "";
        if (second < 4) {
            secondText = "[0.4)";
        } else if (second >= 4 && second < 6) {
            secondText = "[4.6)";
        } else if (second >= 6 && second < 10) {
            secondText = "[6.10)";
        } else if (second >= 10) {
            secondText = "[10.)";
        }
        return secondText;
    }

    /**
     * 换脸接口成功，统计耗时区间
     *
     * @param second 耗时区间
     */
    private void requestSucceedStat(String second) {
//        StatisticsUtils.statisicsCustomFunction(UMENG_CUSTOM_EVENT_EDITOR, UMENG_CUSTOM_KEY_FUNCTION,
//                StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_MAINPAGE +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.MAIN_BTN_SWAP +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.FACE_SWAP_REQUEST_SUCCESS +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        second
//        );
    }

    /**
     * 压缩图片，请求接口
     */
    private void compressAndRequest() {
        if (!TextUtils.isEmpty(mResultBase64)) {
            showSwapPic(mResultBase64);
            return;
        }
        showLoading();
        ThreadPool.runOnNonUIThread(new Runnable() {
            @Override
            public void run() {
                if (mResultBean == null) {
                    if (mOnEventListener != null) {
                        mOnEventListener.updateResultBean();
                    }
                    return;
                }
                //增加压缩缓存，因为原图和模板合并，原图pic是固定，只需要压缩一次，就可以，下次请求可以复用
                if (!TextUtils.isEmpty(mCompressPic)) {
                    requestSwap(mCompressPic);
                    return;
                }
                //
                Bitmap bitmap = ImageHelper.getBitmapFromPath(mImagePath);
                if (bitmap == null){
                    Toast.makeText(mActivity, "bitmap is empty", Toast.LENGTH_SHORT).show();
                    return;
                }
                //压缩图片
                Bitmap bitmap1 = ImageHelper.compressJpgToLimitKB(bitmap, 100);
                if (bitmap1 == null){
                    Toast.makeText(mActivity, "bitmap is empty", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    mCompressPic = ImageHelper.bitmapToBase64(bitmap1);
                    DLog.i(TAG, "onSuccess: compressImage");
                    requestSwap(mCompressPic);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private long startRequest;

    private void requestSwap(String pic) {
        startRequest = System.currentTimeMillis();
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_PAST_LIFE);

        DLog.e(TAG, "requestSwap");
        FaceUtil.requestPastLife(pic, mResultBean.getGender().toLowerCase(), mResultBean.getEthnicity().toLowerCase(), this, new FaceBaseCallback() {
            @Override
            public void onSuccess(Response response) {
                DLog.e(TAG, "requestSwap -> success");
                //network error
                if (!NetworkUtils.isNetworkAvailable(mActivity)){
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_FAIL,
                            StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                            StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_PAST_LIFE,
                            StatisticsConstant.KEY_RESULT_FAIL_REASON, "network");
                    return;
                }
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_SUCCESS,
                        StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                        StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_PAST_LIFE,
                        StatisticsConstant.KEY_REQUEST_TIME, getTimeInterval(startRequest));

                okhttp3.Response rawResponse = response.getRawResponse();
                if (rawResponse == null) {
                    hideLoading();
                    tryGetTemplatesAgain();
                    return;
                }
                ResponseBody responseBody = rawResponse.body();
                if (responseBody == null) {
                    hideLoading();
                    tryGetTemplatesAgain();
                    return;
                }
                new ParseBodyTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, responseBody);
            }

            @Override
            public void onError(Response response) {
                hideLoading();
                DLog.e(TAG, "requestSwap -> onError");
                tryGetTemplatesAgain();
                statisFaild();
                ToastUtil.showToast(R.string.gender_swap_failed);
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_FAIL,
                        StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                        StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_PAST_LIFE,
                        StatisticsConstant.KEY_RESULT_FAIL_REASON, response.message());
            }
        });
    }

    public class SimpleData {
        public String birthYear;
        public String life;
        public String career;
        public String base64;
        public String profile;
        public String lesson;
    }

    class ParseBodyTask extends AsyncTask<ResponseBody, Void, SimpleData> {
        @Override
        protected SimpleData doInBackground(ResponseBody... responseBodies) {
            if (responseBodies == null || responseBodies.length < 1) {
                return null;
            }
            ResponseBody responseBody = responseBodies[0];
            try {
                String result = responseBody.string();
                if (TextUtils.isEmpty(result)) {
                    hideLoading();
                    return null;
                }
                JSONObject jsonObject = new JSONObject(result);
                int code = jsonObject.optInt("code");
                if (code == 3) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            hideLoading();
                            ToastUtil.showToast(R.string.concurrency_limit_tip);
                        }
                    });
                    return null;
                }
                if (!jsonObject.optBoolean("success")) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            hideLoading();
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                JSONObject dataJson = jsonObject.optJSONObject("data");
                if (dataJson == null) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                String picBase64 = (String) dataJson.get("pic");
                if (TextUtils.isEmpty(picBase64)) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            hideLoading();
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                //统计
//                requestSucceedStat(getTimeInterval(startRequest));
                DLog.i(TAG, "onSuccess: " + picBase64);
                //cache
                SimpleData data = new SimpleData();
                data.birthYear = dataJson.optString("birth");
                data.life = dataJson.optString("lifetime");
                data.career = dataJson.optString("profession");
                data.base64 = picBase64;
                data.profile = dataJson.optString("experience");
                data.lesson = dataJson.optString("journey");
                return data;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            tryGetTemplatesAgain();
            return null;
        }

        @Override
        protected void onPostExecute(SimpleData data) {
            if (data == null) {
                tryGetTemplatesAgain();
                statisFaild();
                return;
            }
            mResultBase64 = data.base64;
            if (!TextUtils.isEmpty(mResultBase64)) {
                hideLoading();
                //显示到image view
                showSwapPic(mResultBase64);
            }
            mLifeLayout.setVisibility(View.VISIBLE);
            mLessonLayout.setVisibility(View.VISIBLE);
            String picBase64 = data.base64;
            if (!TextUtils.isEmpty(picBase64)) {
                processBitmap(BitmapUtils.base64ToBitmap(picBase64));
            }
            String birthYear = data.birthYear;
            if (!TextUtils.isEmpty(birthYear)) {
                mTvBirthYear.setText(birthYear);
            }
            String life = data.life;
            if (!TextUtils.isEmpty(life)) {
                mTvLife.setText(life);
            }
            String career = data.career;
            if (!TextUtils.isEmpty(career)) {
                mTvCareer.setText(captureWord(career));
            }
            String profile = data.profile;
            if (!TextUtils.isEmpty(profile)) {
                mProfileContent.setText(profile);
            }
            String lesson = data.lesson;
            if (!TextUtils.isEmpty(lesson)) {
                mLessonContent.setText(lesson);
            }
            hideLoading();
        }
    }

    private String captureWord(String name) {
        char[] cs=name.toCharArray();
        cs[0]-=32;
        return String.valueOf(cs);
    }

    private void processBitmap(final Bitmap bitmap) {
        ThreadPool.runOnNonUIThread(new Runnable() {
            @Override
            public void run() {
                GPUImageFilter filter1 = new GPUImageLookupFilter();
                Bitmap hue = BitmapFactory.decodeResource(ComponentContext.getContext().getResources(), R.drawable.source1);
                ((GPUImageLookupFilter) filter1).setBitmap(hue);
                Bitmap bitmap1 = GPUImage.getBitmapForFilter(bitmap, filter1);
                GPUImageFilter filter2 = new GPUImageTextureFilter();
                Bitmap texture = BitmapFactory.decodeResource(ComponentContext.getContext().getResources(), R.drawable.source2);
                ((GPUImageTextureFilter) filter2).setBitmap(texture);
                Bitmap bitmap2 = GPUImage.getBitmapForFilter(bitmap1, filter2);
                if (bitmap2 != null) {
                    mProcessedBitmap = bitmap2;
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            mImgResult.setImageBitmap(mProcessedBitmap);
                        }
                    });
                }
            }
        });
    }

    protected String getStatisticsSuccessType() {
        if (startRequest == 0) {
            startRequest = System.currentTimeMillis();
        }
        long durationSec = (System.currentTimeMillis() - startRequest) / TimeConstant.ONE_SEC;
        if (durationSec <= 4 && durationSec >= 0) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_4;
        } else if (durationSec <= 6) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_6;
        } else if (durationSec <= 10) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_10;
        } else {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_ABOVE_10;
        }
    }

    private void statisFaild() {
        StatisticsUtils.statisticsFaceSecret(StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_PAST_LIFE + "_" +
                StatisticsConstant.STATISTIC_EVENT_VALUE_REPORT_GET_PIC_FAIL + "_"
                + StatisticsConstant.STATISTIC_EVENT_VALUE_REQUEST);
    }

    private void tryGetTemplatesAgain() {
        if (mActivity == null) {
            return;
        }


        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                ToastUtil.showToast(R.string.gender_swap_failed);
            }
        });
//        FaceUtil.showExitDialog(mActivity,
//                mActivity.getResources().getString(R.string.net_connect_error),
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        mActivity.onBackPressed();
//                    }
//                },
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        compressAndRequest();
//                    }
//                },
//                new FaceUtil.ExitDialogListener() {
//                    @Override
//                    public void onExitDialogShow() {
//
//                    }
//                }
//        );
    }

    @Override
    public Bitmap getSaveImg() {
        if (mProcessedBitmap != null) {
            return mProcessedBitmap;
        } else if (!TextUtils.isEmpty(mCurrentPath)) {
            Bitmap bitmap = BitmapUtils.base64ToBitmap(mCurrentPath);
            if (bitmap == null) {
                bitmap = ImageHelper.getBitmapFromPath(mCurrentPath);
            }
            return bitmap;
        } else {
            return ImageHelper.getBitmapFromPath(mImagePath);
        }
    }

    private void showLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
            mLoadingView.playAnimation();
            mIsLoading = true;
            if (mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).getEmptyView().setVisibility(View.VISIBLE);
            }
        }
    }

    private void hideLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
            mLoadingView.cancelAnimation();
            mIsLoading = false;
            if (mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).getEmptyView().setVisibility(View.GONE);
            }
        }
    }

    /**
     * 显示最终图片的同时，需要更换模糊背景，更换模糊背景genBackground，直接rx子线程执行。
     *
     * @param pic
     */
    private void showSwapPic(final String pic) {
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                ImageLoader.loadImageFromBase64(ComponentContext.getContext(), pic, mImgResult);
                mCurrentPath = pic;
            }
        });
    }

    @Override
    public int getReportTitleResId() {
        return R.string.past_life;
    }

    @Override
    public String getFeatureType() {
        return StatisticsConstant.STATISTIC_EVENT_FEATURE_VALUE_FEATURE_PAST_LIFE;
    }

    @Override
    public boolean needScrool() {
        return true;
    }


    @Override
    public boolean titleBarWithoutBg() {
        return true;
    }

    public void destroy() {
        mActivity = null;
        OkGo.getInstance().cancelTag(this);
    }

}
